<template>
    <div class="app-container">
        <div class="search-container">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <#list queryList as fieldConfig>
                        <el-form-item
                                <#if fieldConfig.fieldComment??>
                                    label="${fieldConfig.fieldComment}"
                                </#if>
                                prop="${fieldConfig.attrName}">
                            <#if fieldConfig.formType?upper_case == "INPUT" || fieldConfig.formType?upper_case == "TEXT">
                                <el-input
                                        v-model="queryParams.${fieldConfig.attrName}"
                                        placeholder="${fieldConfig.fieldComment}"
                                        clearable
                                        @keyup.enter="handleQuery"
                                />
                            <#elseif fieldConfig.formType?upper_case == "SELECT">
                                <#if fieldConfig.formDict??>
                                    <dictionary v-model="queryParams.${fieldConfig.attrName}" code="${fieldConfig.formDict}"/>
                                <#else>
                                    <el-select v-model="queryParams.${fieldConfig.attrName}"
                                               placeholder="请选择${fieldConfig.fieldComment}">
                                        <el-option :key="1" :value="1" label="选项一"/>
                                        <el-option :key="2" :value="2" label="选项二"/>
                                    </el-select>
                                </#if>
                            <#elseif fieldConfig.formType?upper_case == "RADIO">
                                <el-radio-group v-model="queryParams.${fieldConfig.attrName}">
                                    <el-radio :key="1" :label="1">选项一</el-radio>
                                    <el-radio :key="2" :label="2">选项二</el-radio>
                                </el-radio-group>
                            <#elseif fieldConfig.formType?upper_case == "CHECK_BOX">
                                <el-checkbox-group v-model="queryParams.${fieldConfig.attrName}">
                                    <el-checkbox :key="1" :label="1">选项一</el-checkbox>
                                    <el-checkbox :key="2" :label="2">选项二</el-checkbox>
                                </el-checkbox-group>
                            <#elseif fieldConfig.formType?upper_case == "INPUT_NUMBER">
                                <el-input-number
                                        v-model="queryParams.${fieldConfig.attrName}"
                                        placeholder="${fieldConfig.fieldComment}"
                                />
                            <#elseif fieldConfig.formType?upper_case == "SWITCH">
                                <el-switch
                                        v-model="queryParams.${fieldConfig.attrName}"
                                        :active-value="1"
                                        :inactive-value="0"
                                />
                            <#elseif fieldConfig.formType?upper_case == "TEXT_AREA">
                                <el-input type="textarea"
                                          v-model="queryParams.${fieldConfig.attrName}"
                                          placeholder="${fieldConfig.fieldComment}"
                                />
                            <#elseif fieldConfig.formType?upper_case == "DATE_TIME">
                                <el-date-picker
                                        v-model="queryParams.${fieldConfig.attrName}"
                                        <#if fieldConfig.queryType?upper_case == "BETWEEN">
                                            type="daterange"
                                            range-separator="~"
                                            start-placeholder="开始时间"
                                            end-placeholder="结束时间"
                                        <#else>
                                            type="datetime"
                                            placeholder="${fieldConfig.fieldComment}"
                                        </#if>
                                        value-format="YYYY-MM-DD HH:mm:ss"
                                />
                            <#elseif fieldConfig.formType?upper_case == "DATE">
                                <el-date-picker
                                        class="!w-[240px]"
                                        v-model="queryParams.${fieldConfig.attrName}"
                                        <#if fieldConfig.queryType?upper_case == "BETWEEN">
                                            type="daterange"
                                            range-separator="~"
                                            start-placeholder="开始时间"
                                            end-placeholder="结束时间"
                                        <#else>
                                            type="date"
                                            placeholder="${fieldConfig.fieldComment}"
                                        </#if>
                                        value-format="YYYY-MM-DD"
                                />
                            </#if>
                        </el-form-item>
                </#list>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">
                        <i-ep-search/>
                        搜索
                    </el-button>
                    <el-button @click="handleResetQuery">
                        <i-ep-refresh/>
                        重置
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-card shadow="never" class="table-container">
            <template #header>
                <el-button
                        v-hasPerm="['${moduleName}:${ClassName?lower_case}:add']"
                        type="success"
                        @click="handleOpenDialog()"
                >
                    <i-ep-plus/>
                    新增
                </el-button>
                <el-button
                        v-hasPerm="['${moduleName}:${ClassName?lower_case}:delete']"
                        type="danger"
                        :disabled="removeIds.length === 0"
                        @click="handleDelete()"
                >
                    <i-ep-delete/>
                    删除
                </el-button>
            </template>

            <el-table
                    ref="dataTableRef"
                    v-loading="loading"
                    :data="pageData"
                    highlight-current-row
                    border
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"/>
                <#list gridList as fieldConfig>
                        <el-table-column
                                key="${fieldConfig.attrName}"
                                <#if fieldConfig.fieldComment??>label="${fieldConfig.fieldComment}"</#if>
                                prop="${fieldConfig.attrName}"
                                min-width="100"
                        />
                </#list>
                <el-table-column fixed="right" label="操作" width="220">
                    <template #default="scope">
                        <el-button
                                v-hasPerm="['${moduleName}:${ClassName?lower_case}:edit']"
                                type="primary"
                                size="small"
                                link
                                @click="handleOpenDialog(scope.row.id)"
                        >
                            <i-ep-edit/>
                            编辑
                        </el-button>
                        <el-button
                                v-hasPerm="['${moduleName}:${ClassName?lower_case}:delete']"
                                type="danger"
                                size="small"
                                link
                                @click="handleDelete(scope.row.id)"
                        >
                            <i-ep-delete/>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination
                    v-if="total > 0"
                    v-model:total="total"
                    v-model:page="queryParams.current"
                    v-model:limit="queryParams.size"
                    @pagination="handleQuery()"
            />
        </el-card>

        <!-- ${tableComment}表单弹窗 -->
        <el-dialog
                v-model="dialog.visible"
                :title="dialog.title"
                width="500px"
                @close="handleCloseDialog"
        >
            <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
                <#list formList as fieldConfig>
                <el-form-item
                        <#if fieldConfig.fieldComment??> label="${fieldConfig.fieldComment}"</#if>
                              prop="${fieldConfig.attrName}">
                    <#if fieldConfig.formType?upper_case == "INPUT" || fieldConfig.formType?upper_case == "TEXT">
                    <el-input
                            v-model="formData.${fieldConfig.attrName}"
                            placeholder="${fieldConfig.fieldComment}"
                            clearable
                            @keyup.enter="handleQuery"
                    />
                    <#elseif fieldConfig.formType?upper_case == "SELECT">
                        <#if fieldConfig.dictType??>
                            <dictionary v-model="formData.${fieldConfig.attrName}" code="${fieldConfig.dictType}"/>
                        <#else>
                            <el-select v-model="formData.${fieldConfig.attrName}"
                                       placeholder="请选择${fieldConfig.fieldComment}">
                                <el-option :value="0" label="选项一"/>
                                <el-option :value="1" label="选项二"/>
                            </el-select>
                        </#if>
                    <#elseif fieldConfig.formType?upper_case == "RADIO">
                        <el-radio-group v-model="formData.${fieldConfig.attrName}">
                            <el-radio :value="0">选项一</el-radio>
                            <el-radio :value="1">选项二</el-radio>
                        </el-radio-group>
                    <#elseif fieldConfig.formType?upper_case == "CHECK_BOX">
                        <el-checkbox-group v-model="formData.${fieldConfig.attrName}">
                            <el-checkbox :value="0">选项一</el-checkbox>
                            <el-checkbox :value="1">选项二</el-checkbox>
                        </el-checkbox-group>
                    <#elseif fieldConfig.formType?upper_case == "INPUT_NUMBER">
                        <el-input-number
                                v-model="formData.${fieldConfig.attrName}"
                                placeholder="${fieldConfig.fieldComment}"
                        />
                    <#elseif fieldConfig.formType?upper_case == "SWITCH">
                        <el-switch
                                v-model="formData.${fieldConfig.attrName}"
                                :active-value="1"
                                :inactive-value="0"
                        />
                    <#elseif fieldConfig.formType?upper_case == "TEXT_AREA">
                        <el-input type="textarea"
                                  v-model="formData.${fieldConfig.attrName}"
                                  placeholder="${fieldConfig.fieldComment}"
                        />
                    <#elseif fieldConfig.formType?upper_case == "DATE_TIME">
                        <el-date-picker
                                v-model="formData.${fieldConfig.attrName}"
                                type="datetime"
                                placeholder="${fieldConfig.fieldComment}"
                                value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    <#elseif fieldConfig.formType?upper_case == "DATE">
                    <el-date-picker
                            class="!w-[240px]"
                            v-model="formData.${fieldConfig.attrName}"
                            type="date"
                            placeholder="${fieldConfig.fieldComment}"
                            value-format="YYYY-MM-DD"
                    />
                    </#if>
                </el-form-item>
                </#list>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                    <el-button @click="handleCloseDialog">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
    defineOptions({
        name: "${ClassName}",
        inheritAttrs: false,
    });

    import ${ClassName}API, {${ClassName}Form, ${ClassName}PageQuery, ${ClassName}PageVO} from "@/api/${functionName}";

    const queryFormRef = ref<ElForm>();
    const dataFormRef = ref<ElForm>();

    const loading = ref(false);
    const removeIds = ref<number[]>([]);
    const total = ref(0);

    const queryParams = reactive<${ClassName}PageQuery>({
        current: 1,
        size: 10,
    });

    // ${tableComment}表格数据
    const pageData = ref<${ClassName}PageVO[]>([]);

    // 弹窗
    const dialog = reactive({
        title: "",
        visible: false,
    });

    // ${tableComment}表单数据
    const formData = reactive<${ClassName}Form>({});

    // ${tableComment}表单校验规则
    const rules = reactive({
        <#if fieldList??>
        <#list fieldList as fieldConfig>
        <#if fieldConfig.formRequired>
        ${fieldConfig.fieldName}: [{
            required: true,
            message: "请输入${fieldConfig.fieldComment}",
            trigger: "blur"
        }],
        </#if>
        </#list>
        </#if>
    });

    /** 查询${tableComment} */
    function handleQuery() {
        loading.value = true;
        ${ClassName}API.getPage(queryParams)
            .then((data) => {
                pageData.value = data.list;
                total.value = data.total;
            })
            .finally(() => {
                loading.value = false;
            });
    }

    /** 重置${tableComment}查询 */
    function handleResetQuery() {
        queryFormRef.value!.resetFields();
        queryParams.current = 1;
        handleQuery();
    }

    /** 行复选框选中记录选中ID集合 */
    function handleSelectionChange(selection: any) {
        removeIds.value = selection.map((item: any) => item.id);
    }

    /** 打开${tableComment}弹窗 */
    function handleOpenDialog(id?: number) {
        dialog.visible = true;
        if (id) {
            dialog.title = "修改${tableComment}";
            ${ClassName}API.getFormData(id).then((data) => {
                Object.assign(formData, data);
            });
        } else {
            dialog.title = "新增${tableComment}";
        }
    }

    /** 提交${tableComment}表单 */
    function handleSubmit() {
        dataFormRef.value.validate((valid: any) => {
            if (valid) {
                loading.value = true;
                const id = formData.id;
                if (id) {
                    ${ClassName}API.update(formData)
                        .then(() => {
                            ElMessage.success("修改成功");
                            handleCloseDialog();
                            handleResetQuery();
                        })
                        .finally(() => (loading.value = false));
                } else {
                    ${ClassName}API.add(formData)
                        .then(() => {
                            ElMessage.success("新增成功");
                            handleCloseDialog();
                            handleResetQuery();
                        })
                        .finally(() => (loading.value = false));
                }
            }
        });
    }

    /** 关闭${tableComment}弹窗 */
    function handleCloseDialog() {
        dialog.visible = false;
        dataFormRef.value.resetFields();
        dataFormRef.value.clearValidate();
        formData.id = undefined;
    }

    /** 删除${tableComment} */
    function handleDelete(id?: number) {
        const ids = [id || removeIds.value].join(",");
        if (!ids) {
            ElMessage.warning("请勾选删除项");
            return;
        }

        ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(
            () => {
                loading.value = true;
                ${ClassName}API.deleteByIds(ids)
                    .then(() => {
                        ElMessage.success("删除成功");
                        handleResetQuery();
                    })
                    .finally(() => (loading.value = false));
            },
            () => {
                ElMessage.info("已取消删除");
            }
        );
    }

    onMounted(() => {
        handleQuery();
    });
</script>
